<template>
  <!-- 确认订单 -->
  <view>
    <c-navBar title="确认订单" isPerch isTran></c-navBar>
    <view class="co-bg"></view>

    <!-- 地址信息 -->
    <view class="address" @click="addressShow = true">
      <view
        class="df aic"
        v-if="addressData && addressData != '' && addressData != undefined"
      >
        <image
          class="ad-icon"
          :src="require('@/pages/order/static/address.png')"
          mode=""
        ></image>
        <view>
          <view class="ad-info"
            >{{ addressData.userName }} {{ addressData.phone }}</view
          >
          <view class="ad-font"
            >{{
              addressData.province +
              addressData.city +
              addressData.area +
              addressData.address
            }}
          </view>
        </view>
      </view>
      <view class="ad-please" v-else>请选择收货地址</view>
      <image class="ad-go" src="@/static/common/go2.png" mode=""></image>
    </view>

    <!-- 商品信息 -->
    <view class="sc-shop" v-for="v in orderData.goodsList" :key="v.id">
      <view class="" style="display: flex">
        <view class="sc-img">
          <image :src="v.picture" mode=""></image>
          <!-- <view class="sc-end">距结束：23:56:39</view> -->
        </view>
        <view class="sc-right">
          <view class="sc-title otw">{{ v.title }}</view>
          <view class="sc-text">已选：{{ v.propertiesName }}</view>
          <view class="df aife jcsb mt10">
            <view class="sc-price" v-if="userType == 0">
              <text>￥</text>{{ v.price }}
            </view>
            <view style="display: flex; align-items: center" v-else>
              <view class="sc-price"> <text>￥</text>{{ v.memberPrice }} </view>
              <view class="sh-old"> <text>￥</text>{{ v.price }} </view>
            </view>
            <u-number-box
              v-model="v.quantity"
              disabledInput
              :min="1"
              @minus="handleTab(v, 2)"
              @plus="handleTab(v, 1)"
              @change="valChange"
            ></u-number-box>
            <!-- <view class="sc-num">x{{v.quantity}}</view> -->
          </view>
        </view>
      </view>

      <view
        class="cpbox"
        v-if="option.type == 2"
        @click.stop="goSelectCoupon(v.skuId, v.quantity, 3)"
      >
        <view class="cpbox_l"> 优惠券 </view>
        <view class="cpbox_r">
          {{ v.couponId ? "-￥" + v.discountAmount : "请选择优惠券" }}
          <image
            @click.stop="closeCoupon(v.skuId)"
            class="close"
            v-if="v.couponId"
            :src="require('@/pages/order/static/cha.png')"
            mode="widthFix"
          ></image>
          <image src="@/static/common/go2.png" mode="widthFix"></image>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="expense">
      <view class="ex-box">
        <view class="ex-title">商品总价</view>
        <view class="ex-text"
          >￥{{ orderData.orderSum }}<text>共{{ goodsNum }}件商品</text></view
        >
      </view>
      <view class="ex-box">
        <view class="ex-title">运费</view>
        <view class="ex-text" :class="{ fre: orderData.freight == 0 }"
          >￥{{ orderData.freight }}</view
        >
      </view>
      <view class="ex-box" @click="goSelectCoupon(0, 0, option.type)">
        <view class="ex-title">优惠券</view>
        <view
          class="ex-text"
          v-if="orderData.discountAmount || orderData.discountAmount == 0"
        >
          -￥{{ orderData.discountAmount }}
          <image src="@/static/common/go2.png" mode=""></image>
        </view>
        <view class="ex-text" v-else>
          请选择优惠券
          <image src="@/static/common/go2.png" mode=""></image>
        </view>
      </view>
      <view class="ex-box">
        <view class="ex-title">积分</view>
        <view class="ex-text">{{ orderData.payRattan }}积分</view>
      </view>
      <view class="ex-boxs">
        <view class="ex-title">合计 : </view>
        <view class="ex-text">￥{{ orderData.payPrice }}</view>
      </view>
      <view class="ex-remark">
        <view class="ex-title">留言备注</view>
        <view class="ex-area">
          <!-- <textarea name="" v-model="remarks" placeholder="给平台留言（限50字）" id="" cols="30" rows="10"></textarea> -->
          <u--textarea
            v-model="remarks"
            maxlength="50"
            placeholder="给平台留言（限50字）"
          ></u--textarea>
        </view>
      </view>
    </view>

    <!-- 底部按钮区域 -->
    <view class="ba-box"></view>
    <view class="base">
      <view class="df aic">
        <view class="ba-total"
          >合计：<text>￥{{ orderData.payPrice }}</text></view
        >
        <!-- <view class="ba-num">共{{orderData.goodsSum}}件商品</view> -->
      </view>
      <view class="ba-btn" @click.stop="toPayFn">立即支付</view>
    </view>

    <c-address
      ref="address"
      :show.sync="addressShow"
      @confirm="addConfirm"
      @close="addressShow = false"
    ></c-address>
  </view>
</template>

<script>
export default {
  data() {
    return {
      option: {
        cartList: "",
      },
      addressData: null,
      freight: "",
      payIntegral: "",
      orderData: {
        picture: 0,
        price: 0,
        flashSalePrice: 0,
        goodsList: [],
      },
      remarks: "",
      addressShow: false,
      couponId: "",
      userType: 0,
      //商品数量
      goodsNum: 1,
    };
  },
  onLoad(option) {
    console.log("option", option);
    this.option = option;
    this.getAddressListFn();
    this.getMembership();
    // 商品数量
    if (option.cartList) {
      this.goodsNum = JSON.parse(option.cartList).length;
    }
  },
  onShow() {
    this.getCpn();
    // this.confirmOrderFn()
    this.$refs.address.getAddressListFn();
  },
  destroyed() {
    uni.removeStorageSync("couponList");
    uni.removeStorageSync("couponId");
  },
  methods: {
    async handleTab(val, type) {
      if (this.option.spuId) {
        if (type == 1) {
          this.option.quantity++;
        } else {
          this.option.quantity--;
        }
      } else {
        const { data } = await this.$api.updateCartNumY({
          id: val.id,
          type,
          num: 1,
        });
      }
      this.couponId = "";
      uni.removeStorageSync("couponId");

      this.confirmOrderFn();
    },

    valChange() {
      // this.confirmOrderFn()
    },

    // 取消优惠券
    closeCoupon(id) {
      let couponList = uni.getStorageSync("couponList");
      if (couponList) {
        couponList = JSON.parse(couponList);
        let index = couponList.findIndex((item) => item.skuId == id);
        couponList.splice(index, 1);
        uni.setStorageSync("couponList", JSON.stringify(couponList));

        let arr = JSON.parse(this.option.cartList);
        arr.forEach((item) => {
          if (item.skuId == id) {
            item.couponId = "";
          }
        });
        this.option.cartList = JSON.stringify(arr);
        this.getCpn();
      }
    },

    // 获取会员等级
    getMembership() {
      this.$api.getUserTypeY().then((res) => {
        // console.log(res, '会员dengj');
        // this.userType = res.data;
        this.userType = 1;
      });
    },

    // 选择优惠券
    goSelectCoupon(id, num, type) {
      let quantity = this.orderData.goodsList[0].quantity;
      console.log(this.orderData.goodsList, " this.orderData.goodsList");
      if (type == 2) {
        let skuIds = this.orderData.goodsList.map((item) => {
          return (
            item.skuId +
            "-" +
            item.quantity +
            (item.couponId ? "-" + item.couponId : "")
          );
        });
        console.log(skuIds, "skuIds");
        uni.navigateTo({
          url: `/pages/order/pages/selectCoupon?type=${type}&&skuIds=${JSON.stringify(
            skuIds
          )}`,
        });
      } else if (type == 3) {
        uni.navigateTo({
          url: `/pages/order/pages/selectCoupon?skuId=${id}&&quantity=${num}&&type=${type}`,
        });
        uni.removeStorageSync("couponId");
      } else if (type == 1) {
        uni.navigateTo({
          url: `/pages/order/pages/selectCoupon?skuId=${this.option.skuId}&&quantity=${quantity}&&type=1`,
        });
      }
    },

    // 获取地址列表
    async getAddressListFn() {
      const { data } = await this.$api.addressListY({
        id: this.option.addressId,
      });
      console.log("这是地址列表", data);
      if (data.length > 0) {
        if (this.option.addressId) {
          [this.addressData] = data.filter(
            (v) => v.id == this.option.addressId
          );
        } else {
          [this.addressData] = data.filter((v) => v.defaultValue);
        }
      }
      console.log("this.addressData", this.addressData);
    },
    // 获取确认订单信息
    async confirmOrderFn() {
      const { data } = await this.$api.payOrderInfoY({
        type: this.option.type,
        quantity: this.option.quantity,
        skuId: this.option.skuId,
        spuId: this.option.spuId,
        addressId: this.option.addressId,
        couponId: this.couponId,
        cartList: this.option.cartList
          ? JSON.parse(this.option.cartList)
          : [],
      });
      console.log("订单信息data", data);
	  if (!data) {
		  return;
	  }
      this.orderData = data;
      // this.orderData.goodsList = data.goodsList
      this.orderData.orderSum = 0;
      this.orderData.goodsSum = 0;
      this.orderData.goodsList.forEach((v) => {
        this.orderData.orderSum +=
          this.userType > 0 ? v.memberPrice * v.quantity : v.price * v.quantity;
        this.orderData.goodsSum += v.quantity;
      });
      this.orderData.orderSum = this.orderData.orderSum.toFixed(2);
      // this.orderData.goodsSum = this.orderData.goodsSum.toFixed(2)
      this.orderData.totalSum = (
        this.orderData.orderSum +
        this.orderData.freight -
        this.orderData.payIntegral
      ).toFixed(2);
    },

    // 获取本地存储优惠券
    getCpn() {
      let couponId = uni.getStorageSync("couponId");
      if (couponId) {
        this.couponId = couponId;
      } else {
        this.couponId = "";
      }

      let couponList = uni.getStorageSync("couponList");
      let cartLists = this.option.cartList
        ? JSON.parse(this.option.cartList)
        : [];
      if (couponList) {
        couponList = JSON.parse(couponList);
        cartLists = cartLists.map((item) => {
          couponList.forEach((itx) => {
            if (item.skuId == itx.skuId) {
              item.couponId = itx.couponId;
            }
          });
          return item;
        });

        this.option.cartList = JSON.stringify(cartLists);
      }
      this.confirmOrderFn();
    },

    // 去拉起支付
    async toPayFn() {
      //如果没有地址就结束
      if (!this.addressData) {
        uni.showToast({
          icon: "error",
          title: "请选择地址",
        });
        return;
      }
      try {
        uni.showLoading({
          mask: true,
        });
		console.log(this.option.cartList)
		console.log(this.orderData.goodsList)
		if (this.option.cartList) {
			this.orderData.goodsList.forEach(val=>{
				let item = JSON.parse(this.option.cartList).find(item=>item.skuId===val.skuId && item.spuId===val.spuId)
				val.id = item.id
			})
		}
        const { data, code, msg } = await this.$api.payToPayY({
          addressId: this.addressData.id,
          quantity: this.option.quantity,
          couponId: this.couponId,
          spuId: this.option.spuId,
          type: this.option.type,
          cartList: this.option.cartList ? this.orderData.goodsList : null,
          remarks: this.remarks,
          skuId: this.option.skuId,
        });

        // console.log('code', code);
        if (code == 200 && data.paySignVO) {
          uni.requestPayment({
            provider: "wxpay",
            timeStamp: data.paySignVO.timeStamp,
            nonceStr: data.paySignVO.nonceStr,
            package: data.paySignVO.package,
            signType: data.paySignVO.signType,
            paySign: data.paySignVO.paySign,
            success: (res) => {
              console.log("res", res);
              uni.showToast({
                title: "支付成功",
              });
              uni.reLaunch({
                url: "/pages/order/pages/paySuccess?price=" + data.price,
              });
              uni.hideLoading();
            },
            fail: (err) => {
              console.log("err", err);
              uni.showToast({
                icon: "error",
                title: "取消支付",
                duration: 1000,
              });
              setTimeout(() => {
                uni.redirectTo({
                  url: "/pages/order/pages/myOrder?type=0",
                });
              }, 1000);
              uni.hideLoading();
            },
          });
        } else if (code == 200) {
          uni.showToast({
            title: "支付成功",
          });
          uni.reLaunch({
            url: "/pages/order/pages/paySuccess",
          });
        } else {
          uni.showToast({
            icon: "fail",
            title: msg,
          });
        }
      } catch (e) {
        //TODO handle the exception
        console.log("e", e);
        uni.showToast({
          icon: "error",
          title: "支付失败",
        });
      }
    },
    // 确定地址选择
    addConfirm(e) {
      console.log("e111", e);
      // this.addressFont = e[0].province + e[0].city + e[0].area + e[0].address
      this.addressData = e[0];
      this.addressShow = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.co-bg {
  width: 750rpx;
  height: 320rpx;
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
}

.address {
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  z-index: 3;
  padding: 20rpx 32rpx 24rpx 20rpx;
  border-bottom: 8rpx solid #f6f6f6;

  .ad-icon {
    width: 48rpx;
    height: 48rpx;
    margin-right: 16rpx;
  }

  .ad-go {
    width: 20rpx;
    height: 20rpx;
  }

  .ad-please {
    font-size: 28rpx;
    color: #666666;
  }

  .ad-info {
    font-size: 32rpx;
    font-weight: bold;
    color: #1a1a1a;
  }

  .ad-font {
    font-size: 24rpx;
    font-weight: 400;
    color: #666666;
    margin-top: 16rpx;
  }
}

.sc-shop {
  border-radius: 12rpx;
  position: relative;
  background: #fff;
  // display: flex;
  padding: 18rpx 32rpx;
  border-bottom: 8rpx solid #f6f6f6;

  .sc-img {
    width: 160rpx;
    height: 160rpx;
    border-radius: 12rpx 0rpx 0rpx 12rpx;
    overflow: hidden;
    position: relative;
    flex: none;

    .sc-end {
      position: absolute;
      bottom: 0;
      left: 0;
      width: 100%;
      height: 40rpx;
      background: linear-gradient(90deg, #ff4b57 44%, #ff8326 100%);
      border-radius: 12rpx;
      font-size: 20rpx;
      color: #ffffff;
      text-align: center;
      line-height: 38rpx;
    }

    image {
      width: 100%;
      height: 100%;
    }
  }

  .sc-right {
    padding: 0rpx 0rpx 20rpx 28rpx;
    width: 500rpx;

    .sc-title {
      font-size: 32rpx;
      color: #343840;
    }

    .sc-num {
      font-size: 28rpx;
      font-weight: bold;
      color: #1a1a1a;
    }

    .sc-price {
      font-size: 48rpx;
      font-weight: 800;
      color: #ee3b31;

      text {
        font-size: 24rpx;
      }
    }

    .sh-old {
      font-size: 20rpx;
      font-weight: 400;
      color: #999999;
      line-height: 36rpx;
      text-decoration: line-through;
      margin-left: 6rpx;
    }

    .sc-text {
      font-size: 24rpx;
      font-weight: 400;
      color: #999999;
      margin: 14rpx 0;
    }
  }

  .cpbox {
    padding-top: 30rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-top: 1rpx solid #e6e6e6;

    .cpbox_l {
      font-size: 24rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      color: #333333;
    }

    .cpbox_r {
      font-size: 24rpx;
      font-family: PingFang SC, PingFang SC;
      font-weight: 400;
      color: #666666;
      display: flex;
      align-items: center;

      .close {
        width: 30rpx;
        height: 30rpx;
        margin: 0 10rpx;
      }

      image {
        width: 20rpx;
        height: 20rpx;
      }
    }
  }
}

.expense {
  .ex-box {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #e6e6e6;

    &:nth-last-child(1) {
      border-bottom: 8rpx solid #e6e6e6;
    }

    .ex-text {
      font-size: 28rpx;
      color: #333333;
      text {
        font-size: 24rpx;
        font-family: PingFang SC, PingFang SC;
        font-weight: 400;
        color: #666666;
        margin-left: 40rpx;
      }

      image {
        width: 20rpx;
        height: 20rpx;
        margin-left: 6rpx;
      }

      &.fre {
        font-size: 32rpx;
        color: #999999;
        text-decoration: line-through;
      }
    }
  }

  .ex-boxs {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;
    border-bottom: 1rpx solid #e6e6e6;

    &:nth-last-child(1) {
      border-bottom: 8rpx solid #e6e6e6;
    }

    .ex-text {
      font-size: 32rpx;
      color: #333333;

      image {
        width: 20rpx;
        height: 20rpx;
        margin-left: 6rpx;
      }

      &.fre {
        font-size: 32rpx;
        color: #999999;
        text-decoration: line-through;
      }
    }
  }

  .ex-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333333;
  }

  .ex-remark {
    padding: 32rpx;

    .ex-area {
      width: 686rpx;
      // height: 200rpx;
      background: #f6f6f6;
      border-radius: 8rpx;
      font-size: 24rpx;
      font-weight: 400;
      color: #999999;
      line-height: 24rpx;
      margin-top: 20rpx;
      // padding: 20rpx;
      box-sizing: border-box;

      ::v-deep .u-textarea.data-v-09988a29 {
        background-color: transparent;
        border: none;
      }

      textarea {
      }
    }
  }
}

.ba-box {
  height: calc(130rpx + env(safe-area-inset-bottom));
}

.base {
  position: fixed;
  z-index: 999;
  bottom: 0;
  left: 0;
  padding: 24rpx 32rpx calc(24rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
  border-top: 1rpx solid #e6e6e6;
  background: #fff;
  width: 750rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .ba-total {
    font-size: 36rpx;
    font-weight: bold;
    color: #343840;

    text {
      color: #ee3b31;
    }
  }

  .ba-num {
    margin-left: 10rpx;
  }

  .ba-btn {
    width: 240rpx;
    height: 80rpx;
    background: linear-gradient(135deg, #2ad03d 0%, #00b815 100%);
    border-radius: 16rpx 16rpx 16rpx 16rpx;
    font-size: 36rpx;
    font-weight: bold;
    color: #ffffff;
    line-height: 78rpx;
    text-align: center;
  }
}
</style>
